import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/common/LevelOption.dart';
import 'package:ichinesereader/models/evaluation/linguisticKnowledgeResult.dart';
import 'package:ichinesereader/pages/teacher/knowledgeGauge.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:get/get.dart';
import '../../themes/appTheme.dart';

class SkillBuildingWords extends StatefulWidget {
  @override
  State<SkillBuildingWords> createState() => _SkillBuildingWordsState();
}

class _SkillBuildingWordsState extends State<SkillBuildingWords> {
  final box = Hive.box('appconfig');
  final ReportsController controller = Get.find();
  String _classId = '';
  bool isTeacher = false;
  int _currentLevel = 1;

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;

    if (isTeacher) {
      _classId = box.get(CacheManagerKey['currentclass'].toString());
    }

    try {
      _currentLevel = (box.get(CacheManagerKey['eveluationlevel'].toString(),
                                defaultValue: 1) as double)
                            .toInt();
    } catch (error) {
      _currentLevel = 1;
      box.put(CacheManagerKey['eveluationlevel'].toString(), 1.0);
    }

    Future.delayed(Duration(milliseconds: 100), (() {
      if (controller.libraryKnowledgeClassData.value.studentList == null) {
        controller.fetchLibraryKnowledgeClassData(
            _classId, _currentLevel.toString());
      }
    }));

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build skill building words treemap');
    /////Skill Building Words Tab////////
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Column(
          children: [
            Container(
              decoration: BoxDecoration(
                  color: Get.isDarkMode
                      ? AppTheme.colors.darkTheme2
                      : Colors.white.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(3.0)),
              padding: const EdgeInsets.only(left: 12),
              child: FormBuilderChoiceChip(
                spacing: 3.0,
                alignment: WrapAlignment.start,
                labelPadding: EdgeInsets.symmetric(
                  horizontal: 15.0,
                ),
                selectedColor: Get.isDarkMode
                    ? Colors.white
                    : Get.theme.primaryColorDark.withOpacity(0.9),
                elevation: 3.0,
                backgroundColor: Colors.transparent,
                decoration: InputDecoration(
                  //labelText: 'iChineseReader Levels',
                  labelStyle: Get.theme.textTheme.labelSmall,
                  border: InputBorder.none,
                ),

                initialValue: Constants.levelOptions
                    .where((element) =>
                        element.value.toString().replaceAll('level', '') ==
                        _currentLevel.toString())
                    .first,
                //elevation: 0.5,

                name: 'level_filter_chip',
                onChanged: (value) {
                  if (value == null) return;
                  var item = value as LevelOption;
                  int level =
                      int.parse(item.value.toString().replaceAll('level', ''));
                  box.put(CacheManagerKey['eveluationlevel'].toString(),
                      double.parse(level.toString()));
                  controller.fetchLibraryKnowledgeClassData(
                      _classId, level.toString());
                },
                options: Constants.levelOptions
                    .where((element) => element.value != "level0")
                    .map((level) => FormBuilderChipOption<LevelOption>(
                          value: level,
                          child: Text(
                            level.label
                                .toString()
                                .replaceAll('Level 0', 'N/A')
                                .replaceAll('Level ', ''),
                            style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.bold,
                              color: hexStringToHexInt(level.color.toString()),
                              letterSpacing: 0,
                            ),
                          ),
                        ))
                    .toList(),
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(top: 9.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3.0),
                  color: Get.isDarkMode
                      ? AppTheme.colors.darkTheme1
                      : Colors.white.withOpacity(0.3),
                ),
                child: controller.obx(
                  (data) => Container(
                      margin: const EdgeInsets.all(12.0),
                      child: GridView.builder(
                          gridDelegate:
                              const SliverGridDelegateWithMaxCrossAxisExtent(
                                  maxCrossAxisExtent: 200,
                                  childAspectRatio: 156 / 200,
                                  crossAxisSpacing: 10,
                                  mainAxisSpacing: 10),
                          itemCount: controller.libraryKnowledgeClassData.value
                                      .studentList !=
                                  null
                              ? controller.libraryKnowledgeClassData.value
                                  .studentList!.length
                              : 0,
                          itemBuilder: (BuildContext ctx, index) {
                            if (controller.libraryKnowledgeClassData.value
                                    .studentList !=
                                null) {
                              var name =
                                  '${controller.libraryKnowledgeClassData.value.studentList![index].firstName} ${controller.libraryKnowledgeClassData.value.studentList![index].lastName}';
                              return GridTile(
                                  footer: Center(
                                      child: Text(
                                    name,
                                    style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Get.theme.primaryColorDark
                                          : Colors.black,
                                      fontSize: 15.0,
                                    ),
                                  )),
                                  child: InkResponse(
                                      enableFeedback: true,
                                      child: KnowledgeGauge(
                                          studentName: name,
                                          mode: 'water',
                                          progressData: new TotalProgress(
                                              progress: controller
                                                  .libraryKnowledgeClassData
                                                  .value
                                                  .studentList![index]
                                                  .word,
                                              total: controller
                                                  .libraryKnowledgeClassData
                                                  .value
                                                  .studentList![index]
                                                  .total))));
                            } else {
                              return Padding(
                                padding: const EdgeInsets.all(4.0),
                                child: Text(''),
                              );
                            }
                          })),
                  onEmpty: Text('Data not available ...'.tr),
                  onLoading: Container(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
